﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure;
using B.S.BaseData.Write.API.Application.Command;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.BaseData.Write.API.Application.CommandHnadler
{
    public class BreedingUpdateCommandHandler : IRequestHandler<BreedingUpdateCommand, ApiResult<object>>
    {
        // <summary>
        /// 商品信息仓储
        /// </summary>
        private readonly IBaseRepository<BreedingInfo> breedingRepository;

        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="goodsRepository">商品信息仓储</param>
        /// <param name="mapper">映射</param>
        public BreedingUpdateCommandHandler(IBaseRepository<BreedingInfo> breedingRepository, IMapper mapper)
        {
            this.breedingRepository = breedingRepository;
            this.mapper = mapper;
        }
        /// <summary>
        /// 养殖修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<object>> Handle(BreedingUpdateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> result = new ApiResult<object>();

            // 从仓储中获取商品信息
            var brees = await breedingRepository.GetAll().FirstOrDefaultAsync(x => x.BreedId == request.BreedId);

            brees.Variety = request.Variety;
            brees.Source = request.Source;
            brees.FeedingDay = request.FeedingDay;
            brees.Brand = request.Brand;
            brees.Principal = request.Principal;
            brees.LeaveDate = request.LeaveDate;

            // 调用仓储的更新方法
            int rowsAffected = breedingRepository.Update(brees);

            // 设置返回结果
            result.Code = ApiEnums.修改成功;
            result.Msg = ApiEnums.修改成功.ToString();
            result.Data = rowsAffected;

            return await Task.FromResult(result);

        }
    }
}
